package com.mingdao.lhy.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttribute;

import com.linuxense.javadbf.DBFException;
import com.mingdao.lhy.biz.WishFillingBiz;
import com.mingdao.lhy.constant.Constant;
import com.mingdao.lhy.mapper.signup.SignUpStudentMapper2;
import com.mingdao.lhy.mapper.wish.MiddleSchoolMapper;
import com.mingdao.lhy.mapper.wish.PhotoMapper;
import com.mingdao.lhy.mapper.wish.XueJiMapper;
import com.mingdao.lhy.mapper.wish.ZkwMapper;
import com.mingdao.lhy.pojo.MiddleSchool;
import com.mingdao.lhy.pojo.Photo;
import com.mingdao.lhy.pojo.ResponseVo;
import com.mingdao.lhy.pojo.SignUpStudent;
import com.mingdao.lhy.pojo.XueJi;
import com.mingdao.lhy.pojo.Zkw;
import com.mingdao.lhy.pojo.page.ArtSpecialtySignUp;
import com.mingdao.lhy.pojo.page.ArtSpecialtySignUpCity;
import com.mingdao.lhy.pojo.page.ChangePassword;
import com.mingdao.lhy.pojo.signup.SignUpStudent2;
import com.mingdao.lhy.service.CityService;
import com.mingdao.lhy.service.WishFillingService;
import com.mingdao.lhy.util.DbfUtils;
import com.mingdao.lhy.util.NetUtil;

import sun.misc.BASE64Decoder;

@Controller
@RequestMapping("/city")
public class WishCityController {

	private static Logger log = LoggerFactory.getLogger(WishCityController.class);

	@Value("${photopath}")
	private String photoPath;

	@Value("${dbfpath}")
	private String dbfPath;
	
	/**
	 * #报名起止时间
	 */
	@Value("${bmkssj}")
	private String bmkssj;

	@Value("${bmjssj}")
	private String bmjssj;

	@Autowired
	private WishFillingBiz wishFillingBiz;

	@Autowired
	private ZkwMapper zkwMapper;

	@Autowired
	private PhotoMapper photoMapper;

	@Autowired
	private XueJiMapper xueJiMapper;

	@Autowired
	private MiddleSchoolMapper juniorMapper;

	@Autowired
	private CityService cityService;

	@Autowired
	private WishFillingService wishFillingService;

	@Autowired
	private SignUpStudentMapper2 signUpStudentMapper2;

	@RequestMapping("")
	public String index() {
		return "loginCity";
	}

	/**
	 * 县市招办登录验证页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/check", method = RequestMethod.POST)
	public String check(@ModelAttribute("zkw") Zkw zkw, Model model) {

		HttpSession session = wishFillingBiz.getSession();

		log.debug("进入【县市招办登录验证页面】");
		if (null == zkw || null == zkw.getUserid() || null == zkw.getPassword()) {
			log.error("没有收到有效的请求数据");
			model.addAttribute("msg", "没有收到有效的请求数据");
			return "loginCity";
		}

		/**
		 * 如果登录的用户ID不为空，并且不等于"ls710001"和"ls710002"
		 */
		if (null != zkw.getUserid()) {
			if ("ls710001".equals(zkw.getUserid())) {
				log.error("只能是县市教育局登录");
				model.addAttribute("msg", "只能是县市教育局登录");
				return "loginCity";
			} else if ("ls710002".equals(zkw.getUserid())) {
				log.error("只能是县市教育局登录");
				model.addAttribute("msg", "只能是县市教育局登录");
				return "loginCity";
			}
		} else {
			log.error("登录用户不能为空");
			model.addAttribute("msg", "登录用户不能为空");
			return "loginCity";
		}

		/**
		 * 根据县市招办代码查询高中学校信息
		 */
		Zkw zkwDb = new Zkw();
		zkwDb = zkwMapper.getOne(zkw.getUserid());
		if (null == zkwDb) {
			log.error("没有找到指定的县市招办");
			model.addAttribute("msg", "没有找到指定的县市招办");
			return "loginCity";
		}

		/**
		 * 判断县市招办是否第一次登录（如果密码为空，或者和县市招办代码相同则是初次登录）
		 * 
		 * 如果是，跳转到修改密码界面，如果不是，则继续前进到操作选择页面
		 */
		String dbPassword = zkwDb.getPassword().trim();
		if (null == dbPassword || (dbPassword.equals(zkwDb.getUserid()) && dbPassword.equals(zkw.getPassword()))) {
			log.debug("县市招办初次登录 ，进入【密码修改页面】");
			model.addAttribute("zkw", zkwDb);
			session.setAttribute("zkw", zkwDb);
			return "city/changePasswdCity";

		}

		// 验证是否找到对应的县市招办
		// 并且输入的密码是否和查找到的县市办密码是否一致
		if (null != zkwDb.getPassword() && zkwDb.getPassword().equals(zkw.getPassword())) {

			// 验证成功转到填报页面
			log.debug("验证【成功】");
			model.addAttribute("zkw", zkwDb);
			if (null == session) {
				session = wishFillingBiz.getSession();
			}
			session.setAttribute("zkw", zkwDb);

			// 转到艺体特色报名审核页面
			return "city/cityselect";
		} else {
			// 验证失败继续回到登录页面
			// Model model = new Model();
			log.debug("验证【失败】");

			model.addAttribute("msg", "验证失败，招办代码或密码不正确");
			return "loginCity";
		}

	}

	/**
	 * 跳转到修改密码页面
	 * 
	 * @param zkw
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/goChangePasswd", method = RequestMethod.POST)
	public String goChangePasswd(Model model) {
		HttpSession session = wishFillingBiz.getSession();
		if (null == session || null == session.getAttribute("zkw")) {
			session = null;
			log.error("县市招办未登录，请重新登录");
			return "redirect:/loginCity";
		}
		Zkw zkw = (Zkw) session.getAttribute("zkw");
		model.addAttribute("zkw", zkw);
		return "/city/changePasswdCity";

	}

	@RequestMapping(value = "/doChangePasswd", method = RequestMethod.POST)
	public String changePwd(@ModelAttribute(value = "changePassword") ChangePassword changePassword,
			@SessionAttribute Zkw zkw, Model model) {

		HttpSession session = wishFillingBiz.getSession();
		if (null == session || null == session.getAttribute("zkw")) {
			session = null;
			log.error("县市招办未登录，请重新登录");
			return "redirect:/loginCity";
		}
		// zkw = (Zkw) session.getAttribute("zkw");
		/**
		 * 判断传入的密码
		 */
		if (null == model || null == model.asMap() || null == model.asMap().get("changePassword")) {
			log.error("未取到前台返回的密码值 ");
			model.addAttribute("msg", "未取到前台返回的密码值");
			// model.addAttribute("student", student);
			return "/city/changePasswdCity";
		}

		ChangePassword cp = (ChangePassword) model.asMap().get("changePassword");
		if (null == cp.getOldPassword()) {
			log.error("必须输入原来的密码值 ");
			model.addAttribute("msg", "必须输入原来的密码值");
			return "/city/check";
		}
		if (null == cp.getNewPasswordOne() || null == cp.getNewPasswordTwo()) {
			log.error("必须输入新的码值 ");
			model.addAttribute("msg", "必须输入新的码值");
			// model.addAttribute("student", student);
			return "/city/changePasswdCity";
		}

		String oldPassword = cp.getOldPassword();
		String newPasswordOne = cp.getNewPasswordOne();
		String newPasswordTwo = cp.getNewPasswordTwo();

		/**
		 * 如果输入的旧密码等于学生本来的旧密码才可以更换密码
		 */
		if (!oldPassword.isEmpty() && !zkw.getPassword().isEmpty()) {
			if (oldPassword.equals(zkw.getPassword())) {
				/**
				 * 两次输入密码要一致才有效
				 */
				if (newPasswordOne.equals(newPasswordTwo)) {
					zkw.setPassword(newPasswordOne);
				} else {
					log.error("两次密码不符，请重新核对 ");
					model.addAttribute("msg", "两次密码不符，请重新核对 ");
					model.addAttribute("zkw", zkw);
					return "/city/changePasswdCity";
				}
			} else {
				log.error("原密码不符，请重新核对 ");
				model.addAttribute("msg", "原密码不符，请重新核对 ");
				model.addAttribute("zkw", zkw);
				return "/city/changePasswdCity";
			}
		}
		/**
		 * 修改密码
		 */
		int result = cityService.changePassword(zkw);
		if (1 == result) {
			log.debug("密码修改成功");
		} else {
			log.warn("密码修改失败");
			model.addAttribute("zkw", zkw);
			return "city/changePasswdCity";
		}
		/**
		 * 跳转到登录界面重新登录
		 */
		return "loginCity";
	}

	/**
	 * 县市招办管理高中志愿
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping("showHighSchoolInit")
	public String highSchoolWishInit(Model model) {

		HttpSession session = wishFillingBiz.getSession();
		if (null == session || null == session.getAttribute("zkw")) {
			session = null;
			log.error("县市招办未登录，请重新登录");
			return "redirect:/loginCity";
		}
		Zkw zkw = (Zkw) session.getAttribute("zkw");
		model.addAttribute("zkw", zkw);

		/*
		 * List<SignUpStudent> students =
		 * cityService.getWishedStudentByXsdmWished(zkw.getXsdm(), null);
		 */
		/* model.addAttribute("students", students); */

		return "city/CountyEnrolStudent";
	}

	@RequestMapping("showHighSchool")
	@ResponseBody
	public Map<String, Object> highSchoolWish(@ModelAttribute("bmh") String bmh, @ModelAttribute("sele") String sele,
			Model model, @RequestParam int pageSize, @RequestParam int pageIndex) {

		HttpSession session = wishFillingBiz.getSession();
		if (null == session || null == session.getAttribute("zkw")) {
			session = null;
			log.error("县市招办未登录，请重新登录");
			/* return "redirect:/loginCity"; */
		}
		Zkw zkw = (Zkw) session.getAttribute("zkw");
		model.addAttribute("zkw", zkw);
		List<SignUpStudent> students = new ArrayList<SignUpStudent>();
		if ("1".equals(sele)) {
			students = cityService.getWishedStudentByXsdmNotWishedPage(zkw.getXsdm(), bmh, pageSize, pageIndex);
		} else if ("0".equals(sele)) {
			/**
			 * 已填志愿
			 */
			students = cityService.getWishedStudentByXsdmWishedPage(zkw.getXsdm(), bmh, pageSize, pageIndex);
		}

		model.addAttribute("students", students);
		String total = students.get(0).getTotal().toString();
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("total", Integer.parseInt(total));
		result.put("rows", students);
		return result;
		/* return "city/CountyEnrolStudent"; */
	}

	/**
	 * 县市招办管理中职志愿
	 * 
	 * @param model
	 * @return
	 */

	@RequestMapping("showMiddleSchoolInit")
	public String middleShoolWishInit(Model model) {
		HttpSession session = wishFillingBiz.getSession();
		if (null == session || null == session.getAttribute("zkw")) {
			session = null;
			log.error("县市招办未登录，请重新登录");
			return "redirect:/loginCity";
		}
		Zkw zkw = (Zkw) session.getAttribute("zkw");
		model.addAttribute("zkw", zkw);

		/*
		 * List<SignUpStudent> students =
		 * cityService.getWishedStudentByXsdmWishedMiddle(zkw.getXsdm(), null);
		 */
		/* model.addAttribute("students", students); */

		return "city/CountyEnrolMidStudent";
	}

	@RequestMapping("showMiddleSchool")
	@ResponseBody
	public Map<String, Object> middleShoolWish(@ModelAttribute("bmh") String bmh, @ModelAttribute("sele") String sele,
			Model model, @RequestParam int pageSize, @RequestParam int pageIndex) {
		HttpSession session = wishFillingBiz.getSession();
		if (null == session || null == session.getAttribute("zkw")) {
			session = null;
			log.error("县市招办未登录，请重新登录");
			/* return "redirect:/loginCity"; */
		}
		Zkw zkw = (Zkw) session.getAttribute("zkw");
		model.addAttribute("zkw", zkw);
		List<SignUpStudent> students = new ArrayList<SignUpStudent>();
		/**
		 * 未填志愿
		 */
		if ("1".equals(sele)) {
			// students = cityService.getWishedStudentByXsdmNotWishedMiddle(zkw.getXsdm(),
			// bmh);
			students = cityService.getWishedStudentByXsdmNotWishedMiddlePage(zkw.getXsdm(), bmh, pageSize, pageIndex);
		} else if ("0".equals(sele)) {
			/**
			 * 已填志愿
			 */
			// students = cityService.getWishedStudentByXsdmWishedMiddle(zkw.getXsdm(),
			// bmh);
			students = cityService.getWishedStudentByXsdmWishedMiddlePage(zkw.getXsdm(), bmh, pageSize, pageIndex);
		}
		model.addAttribute("students", students);
		String total = students.get(0).getTotal().toString();
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("total", Integer.parseInt(total));
		result.put("rows", students);
		return result;

	}

	/**
	 * 艺体审核
	 * 
	 */

	@RequestMapping("showArtSpecialtyCityInitYt")
	public String showArtSpecialtyCityInitYt(Model model) {

		/**
		 * 审核时间判断 6月22日08:00--6月23日23:59之间可用
		 */
		Date day = new Date();
		HttpSession session = wishFillingBiz.getSession();
		Zkw zkw = (Zkw) session.getAttribute("zkw");
		model.addAttribute("zkw", zkw);

		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			Date now = df.parse(df.format(day)); // 当前时间
			Date startTime = df.parse("2019-06-11 08:00:00");
			Date endTime = df.parse("2019-06-19 23:59:59"); // 截止时间
			if (now.before(endTime) && now.after(startTime)) {
				// 继续正常处理
				System.out.println("继续正常处理");

			} else {
				model.addAttribute("message", "不在审核时间范围内");
				return "city/cityselect";
			}
		} catch (Exception exception) {
			exception.printStackTrace();
			return "city/cityselect";
		}

		if (null == session || null == session.getAttribute("zkw")) {
			session = null;
			log.error("未登录，请重新登录");
			/* return "redirect:/loginStatEnrol"; */
		}

		List<ArtSpecialtySignUp> students = cityService.getWishedStudentByXsdmArtSpecialtyCityYt(zkw.getXsdm());
		model.addAttribute("students", students);

		return "city/wishFillingCityYt";

	}

	@RequestMapping("showArtSpecialtyCityYt")
	@ResponseBody
	public List<ArtSpecialtySignUp> artSpecialtyYt(Model model) {
		HttpSession session = wishFillingBiz.getSession();
		if (null == session || null == session.getAttribute("zkw")) {
			session = null;
			log.error("县市招办未登录，请重新登录");
			// return "redirect:/loginCity";
		}
		Zkw zkw = (Zkw) session.getAttribute("zkw");
		model.addAttribute("zkw", zkw);

		List<ArtSpecialtySignUp> students = cityService.getWishedStudentByXsdmArtSpecialtyCityYt(zkw.getXsdm());
		model.addAttribute("students", students);
		return students;
		// return "city/wishFillingCityTs";
	}

	/**
	 * 特色审核
	 * 
	 */
	@RequestMapping("showArtSpecialtyCityInitTs")
	public String showArtSpecialtyCityInitTs(Model model) {

		/**
		 * 审核时间判断 6月22日08:00--6月23日23:59之间可用
		 */
		Date day = new Date();
		HttpSession session = wishFillingBiz.getSession();
		Zkw zkw = (Zkw) session.getAttribute("zkw");
		model.addAttribute("zkw", zkw);

		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			Date now = df.parse(df.format(day)); // 当前时间
			Date startTime = df.parse("2019-06-11 08:00:00");
			Date endTime = df.parse("2019-06-19 23:59:59"); // 截止时间
			if (now.before(endTime) && now.after(startTime)) {
				// 继续正常处理
				System.out.println("继续正常处理");

			} else {
				model.addAttribute("message", "不在审核时间范围内");
				return "city/cityselect";
			}
		} catch (Exception exception) {
			exception.printStackTrace();
			return "city/cityselect";
		}

		if (null == session || null == session.getAttribute("zkw")) {
			session = null;
			log.error("未登录，请重新登录");
			/* return "redirect:/loginStatEnrol"; */
		}

		List<ArtSpecialtySignUp> students = cityService.getWishedStudentByXsdmArtSpecialtyCityTs(zkw.getXsdm());
		model.addAttribute("students", students);

		return "city/wishFillingCityTs";

	}

	@RequestMapping("showArtSpecialtyCityTs")
	@ResponseBody
	public List<ArtSpecialtySignUp> artSpecialtyTs(@ModelAttribute("bmh") String bmh, Model model) {
		HttpSession session = wishFillingBiz.getSession();
		if (null == session || null == session.getAttribute("zkw")) {
			session = null;
			log.error("县市招办未登录，请重新登录");
			// return "redirect:/loginCity";
		}
		Zkw zkw = (Zkw) session.getAttribute("zkw");
		model.addAttribute("zkw", zkw);

		List<ArtSpecialtySignUp> students = cityService.getWishedStudentByXsdmArtSpecialtyCityTs(zkw.getXsdm());
		model.addAttribute("students", students);
		return students;
		// return "city/wishFillingCityTs";
	}

	/**
	 * 初始化学生密码，一次只能初始化一个学生
	 * 
	 * @param bmh
	 * @return
	 */
	@RequestMapping(value = "doInitPassword", method = RequestMethod.POST)
	@ResponseBody
	public ResponseVo initPassword(@ModelAttribute("bmh") String bmh, Model model) {
		ResponseVo vo = new ResponseVo();
		HttpSession session = wishFillingBiz.getSession();
		if (null == session || null == session.getAttribute("zkw")) {
			session = null;
			log.error("县市招办未登录，请重新登录");
			vo.setCode("error");
			vo.setMessage("县市招办未登录，请重新登录");
			vo.setUrl("redirect:/loginCity");
			// return vo;
		}
		int result = -1;
		// SignUpStudent student = new SignUpStudent();
		Zkw zkw = (Zkw) session.getAttribute("zkw");
		result = wishFillingService.initStudentPassword(bmh);
		if (1 != result) {
			log.warn("密码更新失败");
			vo.setCode("error");
			vo.setMessage("密码更新失败");
			vo.setUrl("city/CountyEnrolStudent");
			// return vo;
		}
		model.addAttribute("zkw", zkw);
		vo.setCode("ok");
		vo.setMessage("密码更新成功");

		vo.setUrl("city/CountyEnrolStudent");
		// return "city/CountyEnrolStudent";
		return vo;
		// return "redirect:/city/CountyEnrolStudent";
		// for (int i = 0; i < students.size(); i++) {
		// SignUpStudent student = students.get(i);
		// result = wishFillingService.initStudentPassword(student);
		// if (1 != result) {
		// log.warn("密码更新失败===>" + student.getBmh() + "===>" + student.getXm());
		// }
		// }

	}

	@RequestMapping("doSelectStudentWishByBmh")
	@ResponseBody
	public List<SignUpStudent> selectStudentWishByBmh(@ModelAttribute("bmh") String bmh,
			@ModelAttribute("sele") String sele, Model model) {
		ResponseVo vo = new ResponseVo();
		HttpSession session = wishFillingBiz.getSession();
		Zkw zkw = (Zkw) session.getAttribute("zkw");
		if (null == session || null == zkw) {
			session = null;
			log.error("县市招办未登录，请重新登录");
			vo.setCode("error");
			vo.setMessage("县市招办未登录，请重新登录");
			vo.setUrl("redirect:/loginCity");
			// return vo;
		}

		if (null == sele || sele.isEmpty()) {
			vo.setCode("stay");
			vo.setMessage("未收到查询条件学生填报类别");
			vo.setUrl("city/CountyEnrolStudent");
			// return vo;
		}

		if (null == bmh || bmh.isEmpty()) {
			vo.setCode("stay");
			vo.setMessage("未收到查询条件报名号");
			vo.setUrl("city/CountyEnrolStudent");
			// return vo;
		}
		List<SignUpStudent> students = new ArrayList<SignUpStudent>();
		/**
		 * 未填志愿
		 */
		if ("1".equals(sele)) {
			students = cityService.getWishedStudentByXsdmNotWished(zkw.getXsdm(), bmh);
		} else if ("0".equals(sele)) {
			/**
			 * 已填志愿
			 */
			students = cityService.getWishedStudentByXsdmWished(zkw.getXsdm(), bmh);
		}

		model.addAttribute("students", students);
		model.addAttribute("zkw", zkw);
		model.addAttribute("sele", sele);
		return students;
		// vo.setCode("ok");
		// vo.setMessage("查询完成");
		/*
		 * vo.setUrl("/city/CountyEnrolStudent");
		 * 
		 * return "/city/CountyEnrolStudent";
		 */
	}

	@RequestMapping(value = "doSelectArtSpecialtyByBmhYt", method = RequestMethod.POST)
	@ResponseBody
	public List<ArtSpecialtySignUp> selectArtSpecialtyByBmhYt(@ModelAttribute("bmh") String bmh,
			@ModelAttribute("sele") String sele, Model model) {
		ResponseVo vo = new ResponseVo();
		HttpSession session = wishFillingBiz.getSession();
		Zkw zkw = (Zkw) session.getAttribute("zkw");
		if (null == session || null == zkw) {
			session = null;
			log.error("县市招办未登录，请重新登录");
			vo.setCode("error");
			vo.setMessage("县市招办未登录，请重新登录");
			vo.setUrl("redirect:/loginCity");
			// return vo;
		}

		if (null == sele || sele.isEmpty()) {
			vo.setCode("stay");
			vo.setMessage("未收到查询条件学生填报类别");
			vo.setUrl("city/wishFillingCityYt");
			// return vo;
		}

		if (null == bmh || bmh.isEmpty()) {
			vo.setCode("stay");
			vo.setMessage("未收到查询条件报名号");
			vo.setUrl("city/wishFillingCityYt");
			// return vo;
		}
		List<ArtSpecialtySignUp> students = new ArrayList<ArtSpecialtySignUp>();

		students = cityService.getArtSpecialtySignUpByXsdmYt(zkw.getXsdm(), bmh);

		model.addAttribute("students", students);
		model.addAttribute("zkw", zkw);
		model.addAttribute("sele", sele);
		return students;
		// vo.setCode("ok");
		// vo.setMessage("查询完成");
		/*
		 * vo.setUrl("city/wishFillingCityYt");
		 * 
		 * return "city/wishFillingCityYt";
		 */
	}

	@RequestMapping(value = "doSelectArtSpecialtyByBmhTs", method = RequestMethod.POST)
	@ResponseBody
	public List<ArtSpecialtySignUp> selectArtSpecialtyByBmhTs(@ModelAttribute("bmh") String bmh,
			@ModelAttribute("sele") String sele, Model model) {
		ResponseVo vo = new ResponseVo();
		HttpSession session = wishFillingBiz.getSession();
		Zkw zkw = (Zkw) session.getAttribute("zkw");
		if (null == session || null == zkw) {
			session = null;
			log.error("县市招办未登录，请重新登录");
			vo.setCode("error");
			vo.setMessage("县市招办未登录，请重新登录");
			vo.setUrl("redirect:/loginCity");
			// return vo;
			/* return "redirect:/loginCity"; */
		}

		if (null == sele || sele.isEmpty()) {
			vo.setCode("stay");
			vo.setMessage("未收到查询条件学生填报类别");
			vo.setUrl("city/wishFillingCityTs");
			// return vo;
			/* return "city/wishFillingCityTs"; */
		}

		if (null == bmh || bmh.isEmpty()) {
			vo.setCode("stay");
			vo.setMessage("未收到查询条件报名号");
			vo.setUrl("city/wishFillingCityTs");
			// return vo;
		}
		List<ArtSpecialtySignUp> students = new ArrayList<ArtSpecialtySignUp>();

		students = cityService.getArtSpecialtySignUpByXsdmTs(zkw.getXsdm(), bmh);

		model.addAttribute("students", students);
		model.addAttribute("zkw", zkw);
		model.addAttribute("sele", sele);
		return students;
		// vo.setCode("ok");
		// vo.setMessage("查询完成");
		/*
		 * vo.setUrl("city/wishFillingCityTs");
		 * 
		 * return "city/wishFillingCityTs";
		 */
	}

	@RequestMapping("doSelectStudentWishByCondition")
	public String selectStudentWishByCondition(@ModelAttribute("sele") String sele, Model model) {
		HttpSession session = wishFillingBiz.getSession();
		ResponseVo vo = new ResponseVo();
		Zkw zkw = (Zkw) session.getAttribute("zkw");
		if (null == session || null == zkw) {
			session = null;
			log.error("县市招办未登录，请重新登录");
			vo.setCode("error");
			vo.setMessage("县市招办未登录，请重新登录");
			vo.setUrl("redirect:/loginCity");
			// return vo;
		}
		if (null == sele || sele.isEmpty()) {
			vo.setCode("stay");
			vo.setMessage("未收到查询条件学生填报类别");
			vo.setUrl("/city/CountyEnrolStudent");
			// return vo;

		}

		List<SignUpStudent> students = new ArrayList<SignUpStudent>();
		/**
		 * 未填志愿
		 */
		if ("1".equals(sele)) {
			students = cityService.getWishedStudentByXsdmNotWished(zkw.getXsdm(), null);
		} else if ("0".equals(sele)) {
			/**
			 * 已填志愿
			 */
			students = cityService.getWishedStudentByXsdmWished(zkw.getXsdm(), null);
		}

		model.addAttribute("students", students);
		model.addAttribute("zkw", zkw);
		model.addAttribute("sele", sele);

		// return vo;
		return "/city/CountyEnrolStudent";
	}

	@RequestMapping("doSelectStudentWishByBmhMiddle")
	public String selectStudentWishByBmhMiddle(@ModelAttribute("bmh") String bmh, @ModelAttribute("sele") String sele,
			Model model) {
		ResponseVo vo = new ResponseVo();
		HttpSession session = wishFillingBiz.getSession();
		Zkw zkw = (Zkw) session.getAttribute("zkw");
		if (null == session || null == zkw) {
			session = null;
			log.error("县市招办未登录，请重新登录");
			vo.setCode("error");
			vo.setMessage("县市招办未登录，请重新登录");
			vo.setUrl("redirect:/loginCity");
			// return vo;
		}

		if (null == sele || sele.isEmpty()) {
			vo.setCode("stay");
			vo.setMessage("未收到查询条件学生填报类别");
			vo.setUrl("city/CountyEnrolMidStudent");
			// return vo;
		}

		if (null == bmh || bmh.isEmpty()) {
			vo.setCode("stay");
			vo.setMessage("未收到查询条件报名号");
			vo.setUrl("city/CountyEnrolMidStudent");
			// return vo;
		}
		List<SignUpStudent> students = new ArrayList<SignUpStudent>();
		/**
		 * 未填志愿
		 */
		if ("1".equals(sele)) {
			students = cityService.getWishedStudentByXsdmNotWishedMiddle(zkw.getXsdm(), bmh);
		} else if ("0".equals(sele)) {
			/**
			 * 已填志愿
			 */
			students = cityService.getWishedStudentByXsdmWishedMiddle(zkw.getXsdm(), bmh);
		}

		model.addAttribute("students", students);
		model.addAttribute("zkw", zkw);
		model.addAttribute("sele", sele);

		// vo.setCode("ok");
		// vo.setMessage("查询完成");
		vo.setUrl("/city/CountyEnrolMidStudent");

		return "/city/CountyEnrolMidStudent";
	}

	@RequestMapping("doSelectStudentWishByConditionMiddle")
	public String selectStudentWishByConditionMiddle(@ModelAttribute("sele") String sele, Model model) {
		HttpSession session = wishFillingBiz.getSession();
		ResponseVo vo = new ResponseVo();
		Zkw zkw = (Zkw) session.getAttribute("zkw");
		if (null == session || null == zkw) {
			session = null;
			log.error("县市招办未登录，请重新登录");
			vo.setCode("error");
			vo.setMessage("县市招办未登录，请重新登录");
			vo.setUrl("redirect:/loginCity");
			// return vo;
		}
		if (null == sele || sele.isEmpty()) {
			vo.setCode("stay");
			vo.setMessage("未收到查询条件学生填报类别");
			vo.setUrl("/city/CountyEnrolMidStudent");
			// return vo;

		}

		List<SignUpStudent> students = new ArrayList<SignUpStudent>();
		/**
		 * 未填志愿
		 */
		if ("1".equals(sele)) {
			students = cityService.getWishedStudentByXsdmNotWishedMiddle(zkw.getXsdm(), null);
		} else if ("0".equals(sele)) {
			/**
			 * 已填志愿
			 */
			students = cityService.getWishedStudentByXsdmWishedMiddle(zkw.getXsdm(), null);
		}

		model.addAttribute("students", students);
		model.addAttribute("zkw", zkw);
		model.addAttribute("sele", sele);

		// return vo;
		return "/city/CountyEnrolMidStudent";
	}

	/**
	 * 单个提交审核状态（艺体特长）
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "doSaveCheckResultYt", method = RequestMethod.POST)
	@ResponseBody
	public ResponseVo saveScoreYt(@ModelAttribute("row") ArtSpecialtySignUpCity artSpecialtySignUpCity, Model model) {
		ResponseVo vo = new ResponseVo();
		HttpSession session = wishFillingBiz.getSession();
		Zkw zkw = (Zkw) session.getAttribute("zkw");
		if (null == session || null == zkw) {
			session = null;
			log.error("县市招办未登录，请重新登录");
			// return "redirect:/loginHighSchool";
			vo.setCode("error");
			vo.setMessage("县市招办未登录，请重新登录");
			vo.setUrl("redirect:/loginCity");
			return vo;
		}
		// String row = (String) model.asMap().get("row");
		/**
		 * 后台数据库保存审核状态
		 */
		// String bmh=(String) model.asMap().get("bmh");
		ArtSpecialtySignUp artSpecialtySignUp = new ArtSpecialtySignUp();
		artSpecialtySignUp.setBmh(artSpecialtySignUpCity.getBmh());
		artSpecialtySignUp.setXsshzt(artSpecialtySignUpCity.getXsshzt());
		int result = cityService.updateArtSpecialtyScoreYt(artSpecialtySignUp);
		if (result != 1) {
			log.error("提交审核状态失败");
			// return "redirect:/loginHighSchool";
			vo.setCode("error");
			vo.setMessage("提交审核状态失败");
			vo.setUrl("city/wishFillingCityYt");
			// return vo;
		} else {
			vo.setCode("ok");
			vo.setMessage("提交成绩成功");
			vo.setUrl("city/wishFillingCityYt");
		}
		// return "highschool/wishFillingHighSchoolTs";
		return vo;
	}

	/**
	 * 单个提交审核状态（特色项目）
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "doSaveCheckResultTs", method = RequestMethod.POST)
	@ResponseBody
	public ResponseVo saveScoreTs(@ModelAttribute("row") ArtSpecialtySignUpCity artSpecialtySignUpCity, Model model) {
		ResponseVo vo = new ResponseVo();
		HttpSession session = wishFillingBiz.getSession();
		Zkw zkw = (Zkw) session.getAttribute("zkw");
		if (null == session || null == zkw) {
			session = null;
			log.error("县市招办未登录，请重新登录");
			// return "redirect:/loginHighSchool";
			vo.setCode("error");
			vo.setMessage("县市招办未登录，请重新登录");
			vo.setUrl("redirect:/loginCity");
			return vo;
		}
		// String row = (String) model.asMap().get("row");
		/**
		 * 后台数据库保存审核状态
		 */
		// String bmh=(String) model.asMap().get("bmh");
		ArtSpecialtySignUp artSpecialtySignUp = new ArtSpecialtySignUp();
		artSpecialtySignUp.setBmh(artSpecialtySignUpCity.getBmh());
		artSpecialtySignUp.setXsshzt(artSpecialtySignUpCity.getXsshzt());
		int result = cityService.updateArtSpecialtyScoreTs(artSpecialtySignUp);
		if (result != 1) {
			log.error("提交审核状态失败");
			// return "redirect:/loginHighSchool";
			vo.setCode("error");
			vo.setMessage("提交审核状态失败");
			vo.setUrl("city/wishFillingCityTs");
			// return vo;
		} else {
			vo.setCode("ok");
			vo.setMessage("提交成绩成功");
			vo.setUrl("city/wishFillingCityTs");
		}
		// return "highschool/wishFillingHighSchoolTs";
		return vo;
	}

	/**
	 * 批量审核通过（特色项目）
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "doExamineTs", method = RequestMethod.POST)
	@ResponseBody
	public ResponseVo examineTs(Model model, @RequestParam("bmh") String bmh) {
		ResponseVo vo = new ResponseVo();
		HttpSession session = wishFillingBiz.getSession();
		Zkw zkw = (Zkw) session.getAttribute("zkw");
		if (null == session || null == zkw) {
			session = null;
			log.error("县市招办未登录，请重新登录");
			// return "redirect:/loginHighSchool";
			vo.setCode("error");
			vo.setMessage("县市招办未登录，请重新登录");
			vo.setUrl("redirect:/loginCity");
			return vo;
		}
		/**
		 * 后台数据库保存审核状态（审核通过）
		 */
		int result = cityService.updateArtSpecialtyExamineByBmhTs(bmh);
		if (result != 1) {
			log.error("审核状态更新失败");
			// return "redirect:/loginHighSchool";
			vo.setCode("error");
			vo.setMessage("审核状态更新失败");
			vo.setUrl("city/wishFillingCityTs");
			return vo;
		}
		vo.setCode("ok");
		vo.setMessage("审核通过更新成功");
		vo.setUrl("city/wishFillingCityTs");
		// return "highschool/wishFillingHighSchoolTs";
		return vo;
	}

	/**
	 * 批量审核通过（艺体特长）
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "doExamineYt", method = RequestMethod.POST)
	@ResponseBody
	public ResponseVo examineYt(Model model, @RequestParam("bmh") String bmh) {
		ResponseVo vo = new ResponseVo();
		HttpSession session = wishFillingBiz.getSession();
		Zkw zkw = (Zkw) session.getAttribute("zkw");
		if (null == session || null == zkw) {
			session = null;
			log.error("县市招办未登录，请重新登录");
			// return "redirect:/loginHighSchool";
			vo.setCode("error");
			vo.setMessage("县市招办未登录，请重新登录");
			vo.setUrl("redirect:/loginCity");
			return vo;
		}
		/**
		 * 后台数据库保存审核状态（审核通过）
		 */
		int result = cityService.updateArtSpecialtyExamineByBmhYt(bmh);
		if (result != 1) {
			log.error("审核状态更新失败");
			// return "redirect:/loginHighSchool";
			vo.setCode("error");
			vo.setMessage("审核状态更新失败");
			vo.setUrl("city/wishFillingCityYt");
			return vo;
		}
		vo.setCode("ok");
		vo.setMessage("审核通过更新成功");
		vo.setUrl("city/wishFillingCityYt");
		// return "highschool/wishFillingHighSchoolTs";
		return vo;
	}

	/**
	 * 批量审核未通过（艺体）
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "doCancelExamineYt", method = RequestMethod.POST)
	@ResponseBody
	public ResponseVo cancelExamineYt(Model model, @RequestParam("bmh") String bmh) {
		ResponseVo vo = new ResponseVo();
		HttpSession session = wishFillingBiz.getSession();
		Zkw zkw = (Zkw) session.getAttribute("zkw");
		if (null == session || null == zkw) {
			session = null;
			log.error("县市招办未登录，请重新登录");
			// return "redirect:/loginHighSchool";
			vo.setCode("error");
			vo.setMessage("县市招办未登录，请重新登录");
			vo.setUrl("redirect:/loginCity");
			return vo;
		}
		/**
		 * 后台数据库保存审核状态（审核未通过）
		 */
		int result = cityService.updateArtSpecialtyCancelExamineByBmhYt(bmh);
		if (result != 1) {
			log.error("审核状态更新失败");
			// return "redirect:/loginHighSchool";
			vo.setCode("error");
			vo.setMessage("审核状态更新失败");
			vo.setUrl("city/wishFillingCityYt");
			return vo;
		}
		vo.setCode("ok");
		vo.setMessage("审核未通过更新成功");
		vo.setUrl("city/wishFillingCityYt");
		// return "highschool/wishFillingHighSchoolTs";
		return vo;
	}

	/**
	 * 批量审核未通过（特色）
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "doCancelExamineTs", method = RequestMethod.POST)
	@ResponseBody
	public ResponseVo cancelExamineTs(Model model, @RequestParam("bmh") String bmh) {
		ResponseVo vo = new ResponseVo();
		HttpSession session = wishFillingBiz.getSession();
		Zkw zkw = (Zkw) session.getAttribute("zkw");
		if (null == session || null == zkw) {
			session = null;
			log.error("县市招办未登录，请重新登录");
			// return "redirect:/loginHighSchool";
			vo.setCode("error");
			vo.setMessage("县市招办未登录，请重新登录");
			vo.setUrl("redirect:/loginCity");
			return vo;
		}
		/**
		 * 后台数据库保存审核状态（审核未通过）
		 */
		int result = cityService.updateArtSpecialtyCancelExamineByBmhTs(bmh);
		if (result != 1) {
			log.error("审核状态更新失败");
			// return "redirect:/loginHighSchool";
			vo.setCode("error");
			vo.setMessage("审核状态更新失败");
			vo.setUrl("city/wishFillingCityTs");
			return vo;
		}
		vo.setCode("ok");
		vo.setMessage("审核未通过更新成功");
		vo.setUrl("city/wishFillingCityTs");
		// return "highschool/wishFillingHighSchoolTs";
		return vo;
	}

	@RequestMapping("forgetPwd")
	public String forgetPwd() {
		return "city/CountyEnrolStudent";
	}

	/**
	 * 县市招办根据确定的规则生成单个报名学生的报名号（单条）
	 * 
	 * @param signUpStudent2
	 * @param model
	 * @return
	 */
	@RequestMapping("doCreateSignUpStudentBmhBySfzh")
	public String createSignUpStudentBmhBySfzh(@RequestParam("byzxdm") String byzxdm, @RequestParam("sfzh") String sfzh,
			Model model, HttpServletResponse response) {
		ResponseVo vo = new ResponseVo();
		HttpSession session = wishFillingBiz.getSession();
		Zkw zkw = (Zkw) session.getAttribute("zkw");
		if (null == session || null == zkw) {
			session = null;
			log.error("县市招办未登录，请重新登录");
			// return "redirect:/loginHighSchool";
			vo.setCode("error");
			vo.setMessage("县市招办未登录，请重新登录");
			vo.setUrl("redirect:/loginCity");
			// return vo;
		}
		model.addAttribute("zkw", zkw);
		
		/**
		 * 报名时间判断
		 */
		Date day = new Date();

		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			response.setCharacterEncoding("UTF-8");

			Date now = df.parse(df.format(day)); // 当前时间
			Date startTime = df.parse(bmkssj);
			Date endTime = df.parse(bmjssj); // 截止时间
			if (now.before(endTime) && now.after(startTime)) {
				// 继续正常处理
				System.out.println("继续正常处理");

			} else {
				model.addAttribute("message", "非报名时间，不能生成报名号");
				response.getWriter().write("<script>alert('非报名时间，不能生成报名号');</script>");
				return "city/cityselect";
			}
		} catch (Exception exception) {
			exception.printStackTrace();
			return "city/cityselect";
		}
		
		SignUpStudent2 signUpStudent2 = new SignUpStudent2();
		signUpStudent2.setByzxdm(byzxdm);
		signUpStudent2.setSfzh(sfzh);

		/**
		 * 调用服务批量生成报名号
		 */
		int result = cityService.createBmhBySfzh(signUpStudent2);
		if (result != 1) {
			log.warn("生成任何报名号有问题，请检查数据是否正确！！");
		}



		/**
		 * 跳转到县市招办管理界面
		 */
		return "/city/cityManageSignUpInfo";
	}

	/**
	 * 县市招办根据确定的规则生成报名学生的报名号
	 * 
	 * @param xsdm
	 * @param model
	 * @return
	 */
	@RequestMapping("doCreateSignUpStudentBmh")
	 @ResponseBody
	public String createSignUpStudentBmh(@RequestParam("xsdm") String xsdm, HttpServletResponse response, Model model) {
		ResponseVo vo = new ResponseVo();
		HttpSession session = wishFillingBiz.getSession();
		Zkw zkw = (Zkw) session.getAttribute("zkw");
		if (null == session || null == zkw) {
			session = null;
			log.error("县市招办未登录，请重新登录");
			// return "redirect:/loginHighSchool";
			vo.setCode("error");
			vo.setMessage("县市招办未登录，请重新登录");
			vo.setUrl("redirect:/loginCity");
			// return vo;
		}
		model.addAttribute("zkw", zkw);
		
		/**
		 * 报名时间判断
		 */
		Date day = new Date();

		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			response.setCharacterEncoding("UTF-8");

			Date now = df.parse(df.format(day)); // 当前时间
			Date startTime = df.parse(bmkssj);
			Date endTime = df.parse(bmjssj); // 截止时间
			if (now.before(endTime) && now.after(startTime)) {
				// 继续正常处理
				System.out.println("继续正常处理");

			} else {
				model.addAttribute("message", "非报名时间，不能生成报名号");
				response.getWriter().write("<script>alert('非报名时间，不能生成报名号');</script>");
				return "city/cityManageSignUpInfo";
			}
		} catch (Exception exception) {
			exception.printStackTrace();
			return "city/cityManageSignUpInfo";
		}
		
		/**
		 * 调用服务批量生成报名号
		 */
		int result = cityService.createBmhBatch(xsdm.substring(0, 4));
		if (result <= 0) {
			log.warn("没有生成任何报名号，请检查数据是否正确！！");

			// return "生成失败";
			return "/city/cityManageSignUpInfo";
		} 
//			else {
//			try {
//				response.setCharacterEncoding("UTF-8");
//				response.getWriter().write("<script>alert('报名号生成成功！');</script>");
//			} catch (IOException e) {
//				e.printStackTrace();
//			}
//		}

		// return "生成成功";
		/**
		 * 跳转到县市招办管理界面
		 */
		return "/city/cityManageSignUpInfo";

	}

	/**
	 * 县市招办管理志愿填报
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping("showManagerSignUpInfo")
	public String managerSignUpInfo(Model model) {

		HttpSession session = wishFillingBiz.getSession();
		if (null == session || null == session.getAttribute("zkw")) {
			session = null;
			log.error("县市招办未登录，请重新登录");
			return "redirect:/loginCity";
		}
		Zkw zkw = (Zkw) session.getAttribute("zkw");
		model.addAttribute("zkw", zkw);

		List<SignUpStudent2> students = signUpStudentMapper2.listByXsdm(zkw.getXsdm());

		model.addAttribute("students", students);

		return "city/cityManageSignUpInfo";
	}

	@RequestMapping("logout")
	public String logou() {
		HttpSession session = wishFillingBiz.getSession();
		if (null != session) {
			session.removeAttribute("zkw");
		}

		return "loginCity";
	}

	/**
	 * 跳转至添加学生页面
	 * 
	 * @return
	 */
	@RequestMapping("addStudent")
	public String addStudent(Model model) {
		HttpSession session = wishFillingBiz.getSession();
		if (null == session || null == session.getAttribute("zkw")) {
			session = null;
			log.error("用户未登录，请重新登录");
			return "redirect:/";
		}
		Zkw zkw = (Zkw) session.getAttribute("zkw");
		model.addAttribute("zkw", zkw);
		return "city/addStudent";
	}

	/**
	 * 根据dclzt获取学生信息
	 * 
	 * @param dclzt
	 * @return
	 */
	@RequestMapping("getStudentByDclzt")
	@ResponseBody
	public List<SignUpStudent> getStudentByDclzt(String dclzt, String xsdm) {
		List<SignUpStudent> list = cityService.getStudentByDclzt(dclzt, xsdm);
		return list;
	}

	/**
	 * 根据dclzt获取学生信息
	 * 
	 * @param dclzt
	 * @return
	 */
	@RequestMapping("getStudentByDclztPage")
	@ResponseBody
	public Map<String, Object> getStudentByDclztPage(Model model, String dclzt, String xsdm,
			@RequestParam String pageSize, @RequestParam String pageIndex, @RequestParam String sfzh) {
		List<SignUpStudent2> list = cityService.getStudentByDclztPage(dclzt, xsdm.substring(0, 4), pageSize, pageIndex, sfzh);
		model.addAttribute("students", list);
		String total = "0";
		if (null != list && list.size() > 0) {
			total = list.get(0).getTotal().toString();
		}
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("total", Integer.parseInt(total));
		result.put("rows", list);
		System.out.println(result.toString());
		return result;
	}

	/**
	 * 获取未报名学生信息
	 * 
	 * @return
	 */
	@RequestMapping("getWBMStudent")
	@ResponseBody
	public Map<String, Object> getWBMStudent(Model model, @RequestParam String pageSize,
			@RequestParam String pageIndex) {
		HttpSession session = wishFillingBiz.getSession();
		if (null == session || null == session.getAttribute("zkw")) {
			session = null;
			log.error("用户未登录，请重新登录");
			return null;
		}
		Zkw zkw = (Zkw) session.getAttribute("zkw");
		model.addAttribute("zkw", zkw);
		String xsdm = zkw.getUserid().substring(0, 4);
		List<SignUpStudent2> list = cityService.getWBMStudent(xsdm, pageSize, pageIndex);
		model.addAttribute("students", list);
		String total = "0";
		if (null != list && list.size() > 0) {
			total = list.get(0).getTotal().toString();
		}
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("total", Integer.parseInt(total));
		result.put("rows", list);
		System.out.println(result.toString());
		return result;
	}

	/**
	 * 学生到招办报名
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "doSaveSignUpStudent", method = RequestMethod.POST)
	public String saveSignUpStudent(@ModelAttribute("signUpStudent") SignUpStudent2 signUpStudent, Model model,
			HttpServletResponse response) {
		HttpSession session = wishFillingBiz.getSession();
		if (null == session || null == session.getAttribute("zkw")) {
			session = null;
			log.error("用户未登录，请重新登录");
			return "loginCity";
		}
		Zkw zkw = (Zkw) session.getAttribute("zkw");
		// add by jxb 2018-12-29 content:if if-else
		String hjd = signUpStudent.getHjd();
		if (!hjd.isEmpty()) {
			// 如果最后一个字符为逗号，则没有选择到最后(街道)
			if (",".equals(hjd.substring(hjd.length() - 1, hjd.length())))
				// 获取最后一个值 ex: 11,22,33, --> 33
				signUpStudent.setHjd(
						hjd.substring(hjd.substring(0, hjd.length() - 1).lastIndexOf(",") + 1, hjd.length() - 1));
			else // 如果最后一个字符不为逗号，那么一定是选择到最后(街道)，获取最后一个街道编码即可
					// 11,22,33,44 ---> 44
				signUpStudent.setHjd(hjd.substring(hjd.lastIndexOf(",") + 1, hjd.length()));
		}

		try {
			response.setCharacterEncoding("UTF-8");
			// String oldSfzh = (String) model.asMap().get("oldSfzh");
			/**
			 * 查询学生的学籍信息，然后跳转到报名信息详细页面
			 */
			SignUpStudent2 signUpStudent2 = signUpStudentMapper2.getOne(signUpStudent.getSfzh());
			// SignUpStudent2 signUpStudent2 = signUpStudentMapper2.getOne(oldsfzh);
			if (null == signUpStudent2) {
				// 待处理状态，1：确定，2：待定
				signUpStudent.setDclzt("1");
				// 处理就读地：学校代码对应的就读地区行政代码
				// TODO
				String xsdm = Constant.xsdm2jdd.get(signUpStudent.getByzxdm().substring(0, 4));
				signUpStudent.setJdd(xsdm);
				// 将学籍库密码复制到报名库
				signUpStudent.setPassword(signUpStudent.getPassword());
				// signUpStudent.setWbxh((signUpStudentMapper2.getMaxWbxh() + 1) + "");
				signUpStudent.setByzxdm(zkw.getUserid());
				signUpStudentMapper2.insertSelective(signUpStudent);
			} else {
				signUpStudentMapper2.updateByStudentSelective(signUpStudent);
				// signUpStudentMapper2.updateByStudentOldSfzh(signUpStudent, oldsfzh);
			}
			model.addAttribute("zkw", zkw);

			response.getWriter().write("<script>alert('保存成功！');</script>");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error(e.getMessage());
			try {
				response.getWriter().write("<script>alert('添加失败');</script>");
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
		// return "";
		// TODO 确定学生报名详情页面名称
		return "city/cityManageSignUpInfo";
	}

	/**
	 * 招办修改学生信息保存
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "doUpdateSignUpStudent", method = RequestMethod.POST)
	public String updateSignUpStudent(@ModelAttribute("signUpStudent") SignUpStudent2 signUpStudent,
			@ModelAttribute("oldsfzh") String oldsfzh, Model model, HttpServletResponse response) {
		HttpSession session = wishFillingBiz.getSession();
		if (null == session || null == session.getAttribute("zkw")) {
			session = null;
			log.error("用户未登录，请重新登录");
			return "loginCity";
		}
		Zkw zkw = (Zkw) session.getAttribute("zkw");
		// add by jxb 2018-12-29 content:if if-else
		String hjd = signUpStudent.getHjd();
		if (!hjd.isEmpty()) {
			// 如果最后一个字符为逗号，则没有选择到最后(街道)
			if (",".equals(hjd.substring(hjd.length() - 1, hjd.length())))
				// 获取最后一个值 ex: 11,22,33, --> 33
				signUpStudent.setHjd(
						hjd.substring(hjd.substring(0, hjd.length() - 1).lastIndexOf(",") + 1, hjd.length() - 1));
			else // 如果最后一个字符不为逗号，那么一定是选择到最后(街道)，获取最后一个街道编码即可
					// 11,22,33,44 ---> 44
				signUpStudent.setHjd(hjd.substring(hjd.lastIndexOf(",") + 1, hjd.length()));
		}

		try {
			response.setCharacterEncoding("UTF-8");
			model.addAttribute("zkw", zkw);
			// String oldSfzh = (String) model.asMap().get("oldSfzh");
			/**
			 * 查询学生的学籍信息，然后跳转到报名信息详细页面
			 */
			// SignUpStudent2 signUpStudent2 =
			// signUpStudentMapper2.getOne(signUpStudent.getSfzh());
			SignUpStudent2 signUpStudent2 = signUpStudentMapper2.getOne(oldsfzh);
			if (null == signUpStudent2) {
				response.getWriter().write("<script>alert('数据不存在！');</script>");
			} else {
				signUpStudentMapper2.updateByStudentOldSfzh(signUpStudent, oldsfzh);
			}
			response.getWriter().write("<script>alert('保存成功！');</script>");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error(e.getMessage());
			try {
				response.getWriter().write("<script>alert('添加失败');</script>");
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
		// return "";
		// TODO 确定学生报名详情页面名称
		return "city/cityManageSignUpInfo";
	}

	// TODO 是否和上面doSaveSignUpStudent重复了？
	@RequestMapping(value = "doSaveStudnet", method = RequestMethod.POST)
	public String addStudnetByCity(SignUpStudent2 student, HttpServletResponse response, Model model) {
		HttpSession session = wishFillingBiz.getSession();
		if (null == session || null == session.getAttribute("zkw")) {
			session = null;
			log.error("用户未登录，请重新登录");
			return "loginCity";
		}
		Zkw zkw = (Zkw) session.getAttribute("zkw");
		model.addAttribute("zkw", zkw);
		try {

			response.setCharacterEncoding("UTF-8");

			// 设定毕业中学代码 TODO update_user需要，但byzxdm不应该是招办代码
			student.setByzxdm(zkw.getUserid());
			student.setPassword(student.getSfzh().substring(10, 18));
			student.setDclzt("1");
			String xsdm = student.getByzxdm().substring(0, 4);
			student.setJdd(Constant.xsdm2jdd.get(xsdm));
//			int wbxh = signUpStudentMapper2.getMaxWbxh();
//			student.setWbxh(wbxh + "");

			int count = cityService.doSaveStudnet(student);

			// response.setHeader("Content-type", "text/html;charset=UTF-8");

			if (count > 0)
				response.getWriter().write("<script>alert('添加成功');</script>");
			else
				response.getWriter().write("<script>alert('添加失败');</script>");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error(e.getMessage());
			try {
				response.getWriter().write("<script>alert('添加失败');</script>");
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
		return "city/addStudent";
	}

	/**
	 * 跳转到修改学生信息页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "updateStudents", method = RequestMethod.POST)
	public String updateStudents(@ModelAttribute("signUpStudent") SignUpStudent2 signUpStudent, Model model,
			HttpServletResponse response) {
		HttpSession session = wishFillingBiz.getSession();
		if (null == session || null == session.getAttribute("zkw")) {
			session = null;
			log.error("用户未登录，请重新登录");
			return "redirect:/";
		}
		model.addAttribute("stu", signUpStudent);
		model.addAttribute("zkw", session.getAttribute("zkw"));
		
		/**
		 * 报名时间判断
		 */
		Date day = new Date();

		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			response.setCharacterEncoding("UTF-8");

			Date now = df.parse(df.format(day)); // 当前时间
			Date startTime = df.parse(bmkssj);
			Date endTime = df.parse(bmjssj); // 截止时间
			if (now.before(endTime) && now.after(startTime)) {
				// 继续正常处理
				System.out.println("继续正常处理");

			} else {
				model.addAttribute("message", "非报名时间，不能修改学生");
				response.getWriter().write("<script>alert('非报名时间，不能修改学生');</script>");
				return "city/cityselect";
			}
		} catch (Exception exception) {
			exception.printStackTrace();
			return "city/cityselect";
		}
		
		return "city/updateStudent";
	}

	/**
	 * 跳转到修改学生信息页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "takePhoto", method = RequestMethod.POST)
	public String takePhoto(@RequestParam("sfzh") String sfzh, Model model) {
		HttpSession session = wishFillingBiz.getSession();
		if (null == session || null == session.getAttribute("zkw")) {
			session = null;
			log.error("用户未登录，请重新登录");
			return "redirect:/";
		}
		// model.addAttribute("stu", signUpStudent);
		model.addAttribute("sfzh", sfzh);
		return "city/webcam";
	}

	// base64字符串转化成图片
	@RequestMapping(value = "doSavePhoto", method = RequestMethod.POST)
	public String savePhoto(@RequestParam("imgData") String imgData, @RequestParam("sfzh") String sfzh, Model model) {
		HttpSession session = wishFillingBiz.getSession();
		Zkw zkw = (Zkw) session.getAttribute("zkw");
		if (null == session || null == zkw) {
			session = null;
			log.error("用户未登录，请重新登录");
			return "redirect:/";
		}

		// 对字节数组字符串进行Base64解码并生成图片
		if (imgData == null) {// 图像数据为空
			return "city/webcam";
		}
		// Base64 decoder = new Base64();
		BASE64Decoder decoder = new BASE64Decoder();
		String savePath = photoPath;
		try {
			Date day = new Date();
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

			// Base64解码（好像没什么作用）
			byte[] b = decoder.decodeBuffer(imgData);
//			for (int i = 0; i < b.length; ++i) {
//				if (b[i] < 0) {// 调整异常数据
//					b[i] += 256;
//				}
//			}
			// 用正则去掉开头的"data:image/png;base64,"
			// int i = imgData.indexOf("base64,");
			// imgData = imgData.substring(23);
			// 生成jpeg图片
			if (savePath.endsWith("/")) {
				if (!savePath.endsWith(zkw.getXsdm() + "/")) {
					savePath = savePath + zkw.getXsdm() + "/";
				}

			} else {
				if (!savePath.endsWith(zkw.getXsdm())) {
					savePath = savePath + "/" + zkw.getXsdm() + "/";
				}
			}
			File photoDir = new File(savePath);
			if (!photoDir.exists()) {
				photoDir.mkdir();
			}
			String imgFilePath = savePath + sfzh + ".png";// 新生成的图片
			File file = new File(imgFilePath);
			if (file.exists()) {
				// 提醒照片文件已经存在
				System.out.println(sfzh + "的照片文件已经存在，请确认是否替换？");
				file.delete();
			}
			FileOutputStream out = new FileOutputStream(imgFilePath);
			out.write(b);
			out.flush();
			out.close();

			/**
			 * 保存拍照信息
			 */
			Photo photo = new Photo();
			photo.setSfzh(sfzh);
			photo.setTakeTime(df.format(day));
			photo.setPhotoPath(imgFilePath);
			photo.setCityId(zkw.getXsdm());

			// 不存在则插入，存在则更新
			if (null == photoMapper.getOne(sfzh)) {
				photoMapper.insertSelective(photo);
			} else {
				photoMapper.updatePasswordByPrimaryKey(photo);
			}

			return "city/webcam";
		} catch (Exception e) {
			log.debug(e.getMessage());
			System.out.println(e.getMessage());
			return "city/webcam";
		}
	}

	/**
	 * 导出已报名学生DBF文件
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "exportSignUpStudent")
	@ResponseBody
	public String exportSignUpStudent(HttpServletResponse response, Model model) {
		HttpSession session = wishFillingBiz.getSession();
		Zkw zkw = (Zkw) session.getAttribute("zkw");
		if (null == session || null == zkw) {
			session = null;
			log.error("用户未登录，请重新登录");
			return "loginCity";
		}
//		String xsdm = Constant.xsdm2jdd.get((zkw.getUserid().substring(0, 4)));
		String xsdm =zkw.getUserid().substring(0, 4);
				//.getXsdm();
		List<SignUpStudent2> students = signUpStudentMapper2.listByXsdm(xsdm);
		DbfUtils dbf = new DbfUtils();
		String savePath = dbfPath;
		try {

			if (savePath.endsWith("/")) {
				if (!savePath.endsWith(zkw.getXsdm() + "/")) {
					savePath = savePath + zkw.getXsdm() + "/";
				}

			} else {
				if (!savePath.endsWith(zkw.getXsdm())) {
					savePath = savePath + "/" + zkw.getXsdm() + "/";
				}
			}

			// 判断目录是否存在
			File dir = new File(savePath);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			String filePath = savePath + "ls18bmk.dbf";

			dbf.writeSignUpStudent(students, filePath);

			String path = filePath;
			response.reset();
//			path = URLEncoder.encode(path,"UTF-8");
			response.setHeader("Content-Disposition",
					"attachment;filename=" + filePath.substring(filePath.lastIndexOf("/") + 1));
			OutputStream ous = new BufferedOutputStream(response.getOutputStream());
			response.setContentType("application/octet-stream;charset=utf-8");
			File file = new File(path);
			response.addHeader("Content-Length", "" + file.length());

			try {
				FileInputStream inputStream = new FileInputStream(file);
				int b = 0;
				byte[] buffer = new byte[512];
				do {
					b = inputStream.read(buffer);
					if (b < 0) {
						break;
					}
					ous.write(buffer, 0, b);
				} while (true);
				inputStream.close();
				ous.flush();
				ous.close();

			} catch (IOException e) {
				e.printStackTrace();
			}

		} catch (DBFException | IOException e) {
			e.printStackTrace();
		}

		return "city/cityManageSignUpInfo";
//		return null;
	}

	/**
	 * 导出未报名学生DBF文件
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "exportNotSignUpStudent")
	@ResponseBody
	public String exportNotSignUpStudent(HttpServletResponse response, Model model) {
		HttpSession session = wishFillingBiz.getSession();
		Zkw zkw = (Zkw) session.getAttribute("zkw");
		if (null == session || null == zkw) {
			session = null;
			log.error("用户未登录，请重新登录");
			return "loginCity";
		}

		String xsdm = zkw.getUserid().substring(0, 4);
		List<XueJi> students = xueJiMapper.listByNotSignUpByXsdm(xsdm);
		DbfUtils dbf = new DbfUtils();
		String savePath = dbfPath;
		try {

			if (savePath.endsWith("/")) {
				if (!savePath.endsWith(zkw.getXsdm() + "/")) {
					savePath = savePath + zkw.getXsdm() + "/";
				}

			} else {
				if (!savePath.endsWith(zkw.getXsdm())) {
					savePath = savePath + "/" + zkw.getXsdm() + "/";
				}
			}
			// 判断目录是否存在
			File dir = new File(savePath);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			String filePath = savePath + "czxj.dbf";
			dbf.writeNotSignUpStudent(students, filePath);

			String path = filePath;
			response.reset();
//			path = URLEncoder.encode(path,"UTF-8");
			response.setHeader("Content-Disposition",
					"attachment;filename=" + filePath.substring(filePath.lastIndexOf("/") + 1));
			OutputStream ous = new BufferedOutputStream(response.getOutputStream());
			response.setContentType("application/octet-stream;charset=utf-8");
			File file = new File(path);
			response.addHeader("Content-Length", "" + file.length());
			try {
				FileInputStream inputStream = new FileInputStream(file);
				int b = 0;
				byte[] buffer = new byte[512];
				do {
					b = inputStream.read(buffer);
					if (b < 0) {
						break;
					}
					ous.write(buffer, 0, b);
				} while (true);
				inputStream.close();
				ous.flush();
				ous.close();

			} catch (IOException e) {
				e.printStackTrace();
			}

		} catch (DBFException | IOException e) {
			e.printStackTrace();
		}

		return "city/cityManageSignUpInfo";
	}

	/**
	 * 跳转到修改密码页面
	 * 
	 * @param zkw
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "goResetPasswd", method = RequestMethod.POST)
	public String resetPasswd(Model model) {
		HttpSession session = wishFillingBiz.getSession();
		if (null == session || null == session.getAttribute("zkw")) {
			session = null;
			log.error("县市招办未登录，请重新登录");
			return "redirect:/loginCity";
		}
		Zkw zkw = (Zkw) session.getAttribute("zkw");
		model.addAttribute("zkw", zkw);
		String xsdm = zkw.getUserid();
		List<MiddleSchool> juniors = juniorMapper.listByXsdm(xsdm);
		model.addAttribute("juniorlist", juniors);

		return "/city/resetJuniorPwd";

	}

	/**
	 * 重置初中学校密码
	 * 
	 * @param changePassword
	 * @param junior
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/doResetPasswd", method = RequestMethod.POST)
	public String resetPwd(@ModelAttribute(value = "byzxdm") String byzxdm, HttpServletResponse response, Model model) {

		HttpSession session = wishFillingBiz.getSession();
		if (null == session || null == session.getAttribute("zkw")) {
			session = null;
			log.error("县市招办未登录，请重新登录");
			return "/loginCity";
		}

		Zkw zkw = (Zkw) session.getAttribute("zkw");
		model.addAttribute("zkw", zkw);
		/**
		 * 判断传入的密码
		 */
		if (null == byzxdm || byzxdm.isEmpty()) {
			log.error("未取到要重置密码的学校信息");
			model.addAttribute("msg", "未取到要重置密码的学校信息");
			return "city/resetJuniorPwd";
		}
		MiddleSchool junior = new MiddleSchool();
		junior.setByzxdm(byzxdm);
		junior.setPassword(byzxdm);
		/**
		 * 修改密码
		 */
		try {
			response.setCharacterEncoding("UTF-8");

			int result = juniorMapper.updatePasswordByPrimaryKey(junior);
			if (1 == result) {
				log.debug("密码修改成功");

				response.getWriter().write("<script>alert('密码修改成功');</script>");

			} else {
				log.warn("密码修改失败");
				response.getWriter().write("<script>alert('密码修改失败');</script>");
				return "city/resetJuniorPwd";
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		String xsdm = zkw.getUserid();
		List<MiddleSchool> juniors = juniorMapper.listByXsdm(xsdm);
		model.addAttribute("juniorlist", juniors);

		/**
		 * 跳转到登录界面重新登录
		 */
		return "city/resetJuniorPwd";
	}

	/**
	 * 
	 * @param response
	 */
	// @RequestMapping(value = "doDownloadDbf", method = RequestMethod.POST)
	public void downloadDbf(HttpServletResponse response, String dbfName) {
		// 得到ClassLoader 先得到Class,在得到ClassLoader
		ClassLoader c1 = this.getClass().getClassLoader();
		// 调用其getResourceAsStream，得到一个InputStream
		URL url = c1.getResource(dbfName);
		// String path = url.getPath();
		String path = dbfName;

		response.reset();
		// 1.设置文件ContentType类型，这样设置，会自动判断下载文件类型
		// response.setContentType("multipart/form-data");
		response.setContentType("application/octet-stream;charset=UTF-8");
		// 2.设置文件头：最后一个参数是设置下载文件名(假如我们叫a.pdf)
//		response.setHeader("Content-Disposition",
//				"attachment;fileName=" + dbfName.substring(dbfName.lastIndexOf("/") + 1));
		response.setHeader("Content-Disposition",
				"attachment;filename*=UTF-8''" + dbfName.substring(dbfName.lastIndexOf("/") + 1));
		ServletOutputStream out;
		// 通过文件路径获得File对象(假如此路径中有一个download.pdf文件)
		File file = new File(path);

		try {
			FileInputStream inputStream = new FileInputStream(file);

			// 3.通过response获取ServletOutputStream对象(out)
			out = response.getOutputStream();
			PrintWriter pw = response.getWriter();

			int b = 0;
			byte[] buffer = new byte[512];
			while (b != -1) {
				b = inputStream.read(buffer);
				// 4.写到输出流(out)中
				out.write(buffer, 0, b);
				// pw.print(buffer);
			}
			inputStream.close();
			out.flush();
			out.close();
			// pw.flush();
			// pw.close();

		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
